<template>
  <CommonDialog v-model="visible" title="文件导入" :loading="loading" :width="600" @submit="submit" @cancel="cancel">
    <Form ref="formEl" :model="formData" :rules="rules" :label-width="60">
      <FormItem label="文件" prop="files">
        <UploadFile v-model="formData.files" />
      </FormItem>
    </Form>
  </CommonDialog>
</template>

<script setup>
import { onMounted, ref, inject } from 'vue'
import { Message } from 'view-ui-plus'

import { myKnowledge } from '@/api/modules/knowledgeBase'

import UploadFile from '@/pages/knowledgeBase/MyKnowledge/CreateKnowledge/components/UploadFile.vue'

const emit = defineEmits(['cancel', 'submit'])

// 是否打开弹窗
const visible = ref(true)

// 加载状态
const loading = ref(false)

const dataId = ref(undefined)
// 表单元素ref
const formEl = ref(null)
// 表单数据
const formData = ref({
  files: []
})

// 表单校验条件
const rules = ref({
  files: [{ required: true, type: 'array', message: '请上传文件', trigger: 'blur' }]
})

const getTypeId = inject('getTypeId')
const filesUpload = (files) => {
  const id = getTypeId()
  return Promise.all(
    files.map((item) => {
      return myKnowledge.cateUpload({
        upload: item,
        id
      })
    })
  )
}

/**
 * 提交表单
 */
const submit = async () => {
  let valid = await formEl.value.validate()
  if (!valid) return

  loading.value = true

  try {
    await filesUpload(formData.value.files)
    
    emit('submit')
    Message.success('文件导入完成')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  visible.value = false
  emit('cancel')
}

/**
 * 初始化对话框
 */
const initDialog = () => {
  // 显示对话框
  visible.value = true
}

defineExpose({
  initDialog
})

onMounted(() => {})
</script>

<style scoped lang="scss">
.flex-form {
  display: flex;
}
.ivu-input-wrapper,
.ivu-select,
.el-select {
  width: 240px;
}
::deep(.ivu-form-item-label) {
  text-align: right;
}
</style>
